﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;

namespace LongSpeed.WebSite.Behaviors
{
    public class Article
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Memo { get; set; }
        /// <summary>
        /// 映射请求地址
        /// </summary>
        public string FromUrl { get; set; }
        /// <summary>
        /// 映射Id
        /// </summary>
        public string UrlMappingId { get; set; }
        public int Part { get; set; }
        private Part _ParentPart;

        public Part ParentPart
        {
            get
            {
                if (_ParentPart == null)
                {
                    _ParentPart = new Part();
                    _ParentPart.Init(this.Part);
                }
                return _ParentPart;
            }
            set { _ParentPart = value; }
        }

        public Article GetArticle(int id, int part)
        {
            string where = string.Format(" ID = {0}", Convert.ToInt32(id));
            where += string.Format(" and PartID = {0}", Convert.ToInt32(part));
            var ds = GetData(where);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Article m = RowToEntity(row);

                    return m;
                }
            }
            return null;
        }
        public IList<Article> GetAllArticle()
        {
            var ds = GetData("");
            IList<Article> articles = new List<Article>();

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Article m = RowToEntity(row);
                    articles.Add(m);
                }
            }
            return articles;
        }
        public IList<Article> GetAllArticleByPart(int part)
        {
            var ds = GetData(" PartID = " + part);
            IList<Article> articles = new List<Article>();

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Article m = RowToEntity(row);

                    articles.Add(m);
                }
            }
            return articles;
        }

        private static Article RowToEntity(DataRow row)
        {
            Article m = new Article()
            {
                ID = Convert.ToInt32(row["ID"]),
                Content = row["Content"] + "",
                Part = Convert.ToInt32(row["PartID"]),
                ReleaseDate = Convert.ToDateTime(row["ReleaseDate"]),
                Title = row["Title"] + "",
                FromUrl = row["FromUrl"] + "",
                Memo = row["Memo"] + "",
                UrlMappingId = row["UrlMappingId"] + ""
            };
            return m;
        }
        public DataSet GetData(string where)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(" SELECT * FROM T_Article ");
            if (!string.IsNullOrEmpty(where))
            {
                strSql.Append(" where  " + where);
            }
            return OleDbHelper.Query(strSql.ToString());
        }

        public IList<Article> GetArticleByPage(int part, int pageIndex, int pageCount, ref int sumPageCount)
        {
            string cmdStr;
            if (pageIndex == 1)
            {
                cmdStr = string.Format(" select top {0} * from T_Article where PartID = @PartID order by ReleaseDate desc", pageCount);
            }
            else
            {
                cmdStr = string.Format(" select top {0} * from T_Article where PartID = @PartID and ID not in (select top {1} ID from T_Article where PartID = @PartID  order by ReleaseDate desc ) order by ReleaseDate desc", pageCount, (pageIndex - 1) * pageCount);
            }

            System.Data.OleDb.OleDbParameter p = new System.Data.OleDb.OleDbParameter("@PartID", System.Data.OleDb.OleDbType.Integer);
            p.Value = part;

            var ds = OleDbHelper.Query(cmdStr, p);
            IList<Article> articles = new List<Article>();

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    Article m = RowToEntity(row);

                    articles.Add(m);
                }
            }

            object sumCount = OleDbHelper.Query("select count(*) from T_Article where  PartID = @PartID ", p).Tables[0].Rows[0][0];
            sumPageCount = sumCount != null ? Convert.ToInt32(sumCount) % pageCount == 0 ? Convert.ToInt32(sumCount) / pageCount : Convert.ToInt32(sumCount) / pageCount + 1 : 0;

            return articles;
        }

        public string GetReleaseDate()
        {
            if (ReleaseDate == null)
            {
                ReleaseDate = DateTime.Now;
            }
            return ReleaseDate.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public bool Save()
        {
            object title, content, memo, fromurl;
            if (this.Title == null) title = DBNull.Value; else title = this.Title;
            if (this.Content == null) content = DBNull.Value; else content = this.Content;
            if (this.Memo == null) memo = DBNull.Value; else memo = this.Memo;
            if (this.FromUrl == null) fromurl = DBNull.Value; else fromurl = this.FromUrl;

            UrlMapping urlMapping = new UrlMapping()
            {
                Args = string.Format("aid={0}&apart={1}", this.ID, this.Part),
                FormAddress = this.FromUrl,
                ToAddress = "~/Main/Article.aspx",
                ID = this.UrlMappingId == "" ? 0 : Convert.ToInt32(this.UrlMappingId)
            };


            string execSql = "";
            if (this.ID == 0)
            {
                urlMapping.Add(urlMapping);
                this.UrlMappingId = urlMapping.ID + "";

                execSql = " insert into  T_Article( Title, Content, [Memo], PartID,FromUrl,UrlMappingId) values ( @Title, @Content, @Memo, @PartID ,@FromUrl,@UrlMappingId) ";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                     new System.Data.OleDb.OleDbParameter("@Title", System.Data.OleDb.OleDbType.VarWChar,255) { Value =  title},
                     new System.Data.OleDb.OleDbParameter("@Content", System.Data.OleDb.OleDbType.LongVarWChar) { Value =  content},
                     new System.Data.OleDb.OleDbParameter("@Memo", System.Data.OleDb.OleDbType.LongVarWChar) { Value =  memo},
                     new System.Data.OleDb.OleDbParameter("@PartID" ,System.Data.OleDb.OleDbType.Integer) { Value =  Convert.ToInt32( this.Part)},
                     new System.Data.OleDb.OleDbParameter("@FromUrl" ,fromurl),
                     new System.Data.OleDb.OleDbParameter("@UrlMappingId" ,this.UrlMappingId)
                };

                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    this.ID = OleDbHelper.GetMaxID("ID", "T_Article");

                    return true;
                }
            }
            else
            {
                urlMapping.Update(urlMapping);
                this.UrlMappingId = urlMapping.ID + "";

                execSql = "update T_Article set Title= @Title, Content=@Content, [Memo]=@Memo,FromUrl=@FromUrl,UrlMappingId=@UrlMappingId where ID = @ID";
                System.Data.OleDb.OleDbParameter[] par = new System.Data.OleDb.OleDbParameter[] {
                     new System.Data.OleDb.OleDbParameter("@Title", System.Data.OleDb.OleDbType.VarWChar,255) { Value =  title},
                     new System.Data.OleDb.OleDbParameter("@Content", System.Data.OleDb.OleDbType.LongVarWChar) { Value =  content},
                     new System.Data.OleDb.OleDbParameter("@Memo", System.Data.OleDb.OleDbType.LongVarWChar) { Value =  memo},
                     new System.Data.OleDb.OleDbParameter("@FromUrl" ,fromurl),
                     new System.Data.OleDb.OleDbParameter("@UrlMappingId" ,this.UrlMappingId),
                     new System.Data.OleDb.OleDbParameter("@ID", System.Data.OleDb.OleDbType.Integer){ Value = this.ID},
                };

                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    return true;
                }
            }

            return false;
        }

        public bool Delete()
        {
            string execSql = "";
            execSql = "delete from T_Article where ID = @ID ";
            System.Data.OleDb.OleDbParameter par = new System.Data.OleDb.OleDbParameter("@ID", System.Data.OleDb.OleDbType.Integer) { Value = this.ID };
            UrlMapping urlmapping = new UrlMapping();

            if (urlmapping.Delete(this.FromUrl))
            {
                if (OleDbHelper.ExecuteSql(execSql, par) > 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
    public enum ArticlePart
    {
        知识导航 = 1,
        站内公告 = 7,
    }
}